package com.yj.springbootstudy.mulThread.imooc;


import com.sun.javafx.scene.control.skin.VirtualFlow;

import java.util.LinkedList;

/**
 * <h1>生产者消费者模型</h1>
 */
public class ProduceFactory {


    private static LinkedList<String> list = new LinkedList<>();
    private static Object lock = new Object();

    public static void produce(String name){
        synchronized (lock) {
            while (list.size() == 10) {
                System.out.println("当前队列已经满了，不能再继续生产商品！");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(name);
            System.out.println("生产者生产了一件商品："+name+";当前商品的总数为："+list.size());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.notify();
        }
    }

    public static void consume(){
        synchronized (lock){
            while (list.size() == 0){
                System.out.println("当前队列为空，没有可以消费的商品！");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            String name = list.removeFirst();
            System.out.println("消费者消费了一件商品："+name+";当前剩余的商品总数为："+list.size());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ProduceFactory produceFactory = new ProduceFactory();
        Produce produce = new Produce(produceFactory);
        Consume consume = new Consume(produceFactory);

        Thread t1 = new Thread(produce,"t1");
        Thread t2 = new Thread(consume,"t2");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

    }

}

class Produce implements Runnable{

    private ProduceFactory produceFactory;

    public Produce(ProduceFactory produceFactory){
        this.produceFactory = produceFactory;
    }

    @Override
    public void run() {
        int i = 0;
        while (true){
            produceFactory.produce(i++ +"");
        }
    }
}


class Consume implements Runnable{

    private ProduceFactory produceFactory;

    public Consume(ProduceFactory produceFactory){
        this.produceFactory = produceFactory;
    }

    @Override
    public void run() {
        while (true){
            produceFactory.consume();
        }
    }
}
